import { createStore } from 'vuex'

export default createStore({
    //定义需要管理的数据
    state: {
        count: 0,
        isFullscreen: false,
        buycarts: []
    },
    getters: {
        totalPrice(state) {
            let total = state.buycarts.reduce((pre, item) => {
                return pre + item.price * item.num;
            }, 0);
            return total;
        },
        totalCount: function(){
            return this.state.count * 10;
        }
    },
    //修改state中的数据
    mutations: {
        setFullscreen(state, payload) {
            state.isFullscreen = payload;
        },
        updateCount: function(context, num){
            context.count += num;
        },
        addBuycarts(state, payload) {
            console.log(state.buycarts);
            state.buycarts.push(payload);
        },
        addBuycartsNum(state, payload) {
            state.buycarts[payload].num++;
        },
        minusBuycartsNum(state, payload) {
            state.buycarts[payload].num--;
            if (state.buycarts[payload].num == 0) {
                state.buycarts.splice(payload, 1);
            }
        }
    },
    //异步修改state中的数据
    actions: {
        asyncUpdateCount: function(context, num){
            setTimeout(function(){
                context.commit('updateCount', num);
            }, 1500)
        }
    },
    modules: {
    }
});
